using System;
using System.Collections.Generic;
using System.Text;

namespace Index.TemporaryFile.Sorting.Merge
{
    public class InputQueue
    {
        private TermEntryFile input;
        private long block_start;
        private long block_end;
        private long offset;
        private Queue<TermEntry> queue;
        private int queue_size;

        public InputQueue(TermEntryFile input, int queue_size, long block_start, long block_end)
        {
            this.queue_size = queue_size;
            this.block_start = block_start;
            this.block_end = block_end;
            this.input = input;
            this.offset = block_start;
            this.queue = new Queue<TermEntry>(queue_size);
        }

        public void FetchToQueue()
        {

            //Console.WriteLine("Kolejka: {0} - {1}, Offset: {2}", block_start, block_end, offset);
            if (offset + queue_size <= block_end + 1)
            {

                TermEntry[] items = input.Read(offset, queue_size);
                offset += queue_size;


                for (int i = 0; i < items.Length; i++)
                {
                    //Console.WriteLine("Kolejka: {0} - {1}, Dodaje: {2} {3} {4}", block_start, block_end, items[i].TermID, items[i].DocumentID, items[i].FreqORPosition);
                    queue.Enqueue(items[i]);
                }
            }
            else
            {
                long left = block_end - offset + 1;

                if (left > 0)
                {

                    TermEntry[] items = input.Read(offset, left);
                 
                    for (int i = 0; i < items.Length; i++)
                    {
                        queue.Enqueue(items[i]);
                    }
                    offset += left;
                }
            }
        }

        public int Count
        {
            get
            {
                if (queue.Count == 0)
                {
                    FetchToQueue();
                }

                return queue.Count;
            }
        }

        public TermEntry Dequeue()
        {
            if (this.queue.Count == 0)
            {
                FetchToQueue();
            }
            return queue.Dequeue();
        }

        public TermEntry Peek()
        {
            if (queue.Count == 0)
            {
                FetchToQueue();
            }
            return queue.Peek();
        }
    }
}
